package cn.gtv.sdk.dcas.api;

import android.content.Context;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.room.Room;

import java.util.ArrayList;
import java.util.List;

import cn.gtv.sdk.dcas.api.db.Event;
import cn.gtv.sdk.dcas.api.db.EventDatabase;

public class EventsManager {

    private EventDatabase database=null;

    public static final int MAX_COUNT = Integer.MAX_VALUE;

    private static  EventsManager ourInstance;

    private EventsManager(Context context) {
        try {
            database = Room.databaseBuilder(context, EventDatabase.class, "dj_dcas_event.db")
                    .enableMultiInstanceInvalidation()
                    .allowMainThreadQueries()
                    .build();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static EventsManager getInstance(Context context) {
        if(ourInstance==null){
            ourInstance = new EventsManager(context);
        }
        return ourInstance;
    }

    public void insert(Event item) {
        try {
            database.eventDao().insert(item);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void insert(String data) {
        Event item=new Event(data);
        insert(item);
    }

    public void insertAll(Event... items) {
        try {
            database.eventDao().insertAll(items);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public List<Event> getAll(){
        try {
            return database.eventDao().getAll();
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ArrayList<Event>();
    }

    public LiveData<List<Event>> getAllLiveData(){
        return database.eventDao().getAllLiveData();
    }

    public void observeAllLiveData(Observer<List<Event>> observer){
        try {
            LiveData<List<Event>> eventLiveData=getAllLiveData();
            eventLiveData.observeForever(observer);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public List<Event> getOldest(int limit){
        try {
            return database.eventDao().getOldest(limit);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ArrayList<>();

    }

    public LiveData<List<Event>> getOldestLiveData(int limit){
        return database.eventDao().getOldestLiveData(limit);
    }

    public int deleteOldest(long updateTime){
        try {
            return database.eventDao().deleteOldest(updateTime);
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }

    public int deleteAll(){
        try {
            return database.eventDao().deleteAll();
        }catch (Exception e){
            e.printStackTrace();
        }
        return -1;
    }
}
